class ListNode {
    val: number
    next: ListNode | null
    constructor(val?: number, next?: ListNode | null) {
        this.val = (val === undefined ? 0 : val)
        this.next = (next === undefined ? null : next)
    }
}
/**
 * https://leetcode-cn.com/problems/reverse-nodes-in-k-group/
 * k个一组翻转链表
 * @param head 
 * @param k 
 */
const reverseKGroup = (head: ListNode | null, k: number): ListNode | null => {
    // 边界条件判断
    if (head === null) return null;
    if (k === 1 || head.next === null) return head;

    // 1. 计算链表的长度
    let lHead: ListNode | null = head,
        len = 0;
    while (lHead !== null) {
        len++;
        lHead = lHead.next;
    }

    // 2. 计算有多少组需要翻转
    let groupCount = ~~(len / k)


    // 3. 对这些组进行翻转
    let dummyHead = new ListNode(0),  // 虚拟头节点
        dHead = dummyHead;
    while (groupCount--) {
        // 1 创建一个新的节点
        let h: ListNode | null = null
        let ck = k,
            prev = head;
        while (ck-- && head !== null) {
            // 保存head的下一个节点
            const n: ListNode | null = head.next;
            head.next = h;
            h = head;
            head = n;
        }

        // 将h拼接到dummyHead上
        dHead.next = h;
        dHead = prev!
    }

    // 如果dHead不为空, 让其指向最后一个还没分组的
    if (dHead !== null) {
        dHead.next = head;
    }

    return dummyHead.next;
};

export {}